import random
import string
from datetime import datetime

from flask import Blueprint, render_template, request, redirect, url_for, jsonify, session, flash
from flask_mail import Message
from werkzeug.security import generate_password_hash, check_password_hash

from exts import db, mail
from models import EmailCaptchaModel
from models import User
from .forms import RegisterForm, LoginForm

bp = Blueprint("user", __name__, url_prefix="/user")


@bp.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        form = LoginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            user = User.query.filter_by(email=email).first()
            if user and check_password_hash(user.password, password):
                session["user_id"] = user.id
                return redirect("/")
            else:
                flash("邮箱和密码不匹配!")
                return redirect(url_for("user.login"))
        else:
            flash("格式错误!")
            return redirect(url_for("user.login"))


@bp.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "GET":
        return render_template("register.html")
    else:
        form = RegisterForm(request.form)
        if form.validate():
            email = form.email.data
            username = form.username.data
            password = form.password.data
            password = generate_password_hash(password)
            user = User(email=email, username=username, password=password)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for("user.login"))
        else:
            return redirect(url_for("user.register"))


# http://127.0.0.1:5000/user/register?email=2713816703%40qq.com&captcha=vrQD&username=ycc&password=123456&password_com=123456

@bp.route("/logout")
def logout():
    session.clear()
    return redirect(url_for('user.login'))


@bp.route("/captcha", methods=["POST"])
def get_captcha():
    email = request.form.get("email")
    letters = string.ascii_letters + string.digits
    captcha = "".join(random.sample(letters, 4))
    if email:
        message = Message(
            subject="知了问答",
            recipients=[email],
            body="【知了问答】验证码：{}".format(captcha)
        )
        mail.send(message)
        captcha_model = EmailCaptchaModel.query.filter_by(email=email).first()
        if captcha_model:
            captcha_model.captcha = captcha
            captcha_model.create_time = datetime.now()
            db.session.commit()
        else:
            captcha_model = EmailCaptchaModel(email=email, captcha=captcha)
            db.session.add(captcha_model)
            db.session.commit()
        return jsonify({"code": 200})
    else:
        return jsonify({"code": 400, "message": "请填写邮箱信息"})

    # if not email:
    #     return jsonify({"code": 400, message: "请填写邮箱信息"})
    # message = Message(
    #     subject="知了问答",
    #     recipients=[email],
    #     body="【知了问答】验证码：{}".format(captcha)
    # )
    # # mail.send_message(message)
    #
    # if captcha_model:
    #     captcha_model.captcha = captcha
    #     captcha_model.create_time = datetime.now()
    #     db.session.commit()
    # else:
    #     captcha_model = EmailCaptchaModel(email=email, captcha=captcha)
    #     db.session.add(captcha_model)
    #     db.session.commit()
    # return jsonify({"code": 200})
